package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Topic;
import com.ruoyi.system.domain.TeacherInfo;
import com.ruoyi.system.service.ITopicService;
import com.ruoyi.system.service.ITeacherInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 题目Controller
 *
 * @author ltr
 * @date 2024-10-22
 */
@RestController
@RequestMapping("/system/topic")
public class TopicController extends BaseController
{
    @Autowired
    private ITopicService topicService;

    @Autowired
    private ITeacherInfoService teacherInfoService;

    // ==================== 教师端接口 ====================

    /**
     * 查询当前教师的题目列表（教师端）
     */
    @PreAuthorize("@ss.hasRole('teacher')")
    @GetMapping("/list")
    public TableDataInfo list(Topic topic)
    {
        // 获取当前登录用户的教师ID
        Long teacherId = getCurrentTeacherId();
        if (teacherId == null) {
            return getDataTable(null);
        }

        startPage();
        List<Topic> list = topicService.selectTopicListByTeacherId(teacherId);
        return getDataTable(list);
    }

    /**
     * 获取题目详细信息（教师端）
     */
    @PreAuthorize("@ss.hasRole('teacher')")
    @GetMapping(value = "/{topicId}")
    public AjaxResult getInfo(@PathVariable("topicId") Long topicId)
    {
        // 检查题目是否属于当前教师
        Long teacherId = getCurrentTeacherId();
        if (teacherId == null || !topicService.checkTopicOwner(topicId, teacherId)) {
            return error("无权访问该题目");
        }
        return success(topicService.selectTopicByTopicId(topicId));
    }

    /**
     * 新增题目（教师端）
     */
    @PreAuthorize("@ss.hasRole('teacher')")
    @Log(title = "题目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Topic topic)
    {
        // 设置当前教师ID
        Long teacherId = getCurrentTeacherId();
        if (teacherId == null) {
            return error("请先完善教师信息");
        }

        topic.setTeacherId(teacherId);
        topic.setCreateBy(getUsername());
        return toAjax(topicService.insertTopic(topic));
    }

    /**
     * 修改题目（教师端）
     */
    @PreAuthorize("@ss.hasRole('teacher')")
    @Log(title = "题目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Topic topic)
    {
        // 检查题目是否属于当前教师
        Long teacherId = getCurrentTeacherId();
        if (teacherId == null || !topicService.checkTopicOwner(topic.getTopicId(), teacherId)) {
            return error("无权修改该题目");
        }

        // 查询题目当前状态
        Topic existingTopic = topicService.selectTopicByTopicId(topic.getTopicId());
        if (existingTopic == null) {
            return error("题目不存在");
        }

        topic.setUpdateBy(getUsername());

        // 判断是否需要提交/更新修改申请
        // 如果题目已通过审核（无论有没有待审核的修改）或者是"修改待审核"状态，都应该更新pending字段
        if ("已通过".equals(existingTopic.getAuditStatus()) || "修改待审核".equals(existingTopic.getAuditStatus())) {
            int result = topicService.submitTopicModification(topic);
            if (result > 0) {
                // 判断是首次提交还是更新修改申请
                if (existingTopic.getHasPendingChanges() != null && existingTopic.getHasPendingChanges() == 1) {
                    return success("修改申请已更新，等待管理员审核");
                } else {
                    return success("修改申请已提交，等待管理员审核");
                }
            } else {
                return error("提交修改申请失败");
            }
        }

        // 其他状态（待审核、已拒绝）可以直接修改正式字段
        return toAjax(topicService.updateTopic(topic));
    }

    /**
     * 删除题目（教师端）
     */
    @PreAuthorize("@ss.hasRole('teacher')")
    @Log(title = "题目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{topicIds}")
    public AjaxResult remove(@PathVariable Long[] topicIds)
    {
        // 检查每个题目是否属于当前教师且可以删除
        Long teacherId = getCurrentTeacherId();
        if (teacherId == null) {
            return error("请先完善教师信息");
        }

        for (Long topicId : topicIds) {
            if (!topicService.checkTopicOwner(topicId, teacherId)) {
                return error("无权删除题目ID为" + topicId + "的题目");
            }
            if (!topicService.checkTopicCanDelete(topicId)) {
                return error("题目ID为" + topicId + "的题目已有学生报名，无法删除");
            }
        }

        return toAjax(topicService.deleteTopicByTopicIds(topicIds));
    }

    /**
     * 导出题目列表（教师端）
     */
    @PreAuthorize("@ss.hasRole('teacher')")
    @Log(title = "题目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Topic topic)
    {
        Long teacherId = getCurrentTeacherId();
        if (teacherId == null) {
            return;
        }

        List<Topic> list = topicService.selectTopicListByTeacherId(teacherId);
        ExcelUtil<Topic> util = new ExcelUtil<Topic>(Topic.class);
        util.exportExcel(response, list, "题目数据");
    }

    // ==================== 管理员端接口 ====================

    /**
     * 查询所有题目列表（管理员端）
     */
    @PreAuthorize("@ss.hasRole('admin') or @ss.hasRole('administrator')")
    @GetMapping("/all")
    public TableDataInfo listAll(Topic topic)
    {
        startPage();
        List<Topic> list = topicService.selectTopicList(topic);
        return getDataTable(list);
    }

    /**
     * 审批通过题目（管理员端）
     */
    @PreAuthorize("@ss.hasRole('admin') or @ss.hasRole('administrator')")
    @Log(title = "题目审批", businessType = BusinessType.UPDATE)
    @PutMapping("/approve/{topicId}")
    public AjaxResult approve(@PathVariable Long topicId)
    {
        return toAjax(topicService.approveTopic(topicId, getUsername()));
    }

    /**
     * 审批拒绝题目（管理员端）
     */
    @PreAuthorize("@ss.hasRole('admin') or @ss.hasRole('administrator')")
    @Log(title = "题目审批", businessType = BusinessType.UPDATE)
    @PutMapping("/reject/{topicId}")
    public AjaxResult reject(@PathVariable Long topicId, @RequestBody Topic topic)
    {
        if (topic.getAuditOpinion() == null || topic.getAuditOpinion().trim().isEmpty()) {
            return error("请填写拒绝理由");
        }
        return toAjax(topicService.rejectTopic(topicId, topic.getAuditOpinion(), getUsername()));
    }

    // ==================== 学生端接口 ====================

    /**
     * 查询已审核通过的题目列表（学生端）
     */
    @PreAuthorize("@ss.hasRole('student')")
    @GetMapping("/approved")
    public TableDataInfo listApproved(Topic topic)
    {
        startPage();
        List<Topic> list = topicService.selectApprovedTopicList(topic);
        return getDataTable(list);
    }

    /**
     * 获取题目详细信息（学生端）
     */
    @PreAuthorize("@ss.hasRole('student')")
    @GetMapping("/detail/{topicId}")
    public AjaxResult getDetail(@PathVariable("topicId") Long topicId)
    {
        Topic topic = topicService.selectTopicByTopicId(topicId);
        if (topic == null) {
            return error("题目不存在");
        }
        return success(topic);
    }

    // ==================== 工具方法 ====================

    /**
     * 获取当前登录用户的教师ID
     */
    private Long getCurrentTeacherId()
    {
        Long userId = getUserId();
        TeacherInfo teacherInfo = teacherInfoService.selectTeacherInfoByUserId(userId);
        return teacherInfo != null ? teacherInfo.getTeacherId() : null;
    }
}